package org.thalien.roleplay.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.inject.Inject;
import com.google.inject.Singleton;

@Singleton
public abstract class GsonServlet<T> extends HttpServlet {

	private static final long serialVersionUID = 8182626774480092177L;
	
	@Inject
	private Gson gson;
	
	protected abstract Class<T> getInputClass();
	
	protected abstract Object handleRequest(T input);

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Object result = null;
		
		if (this.getInputClass() != Void.class) {
			String jsonString = request.getParameter("json");
			T input = gson.fromJson(jsonString, this.getInputClass());
			result = this.handleRequest(input);
		} else {
			result = this.handleRequest(null);
		}
		
		PrintWriter pw = response.getWriter();
		
		if (result != null) {
			String jsonString = gson.toJson(result);
			pw.write(jsonString);
		}
		
		pw.close();
	}
}
